#  -*- coding: utf-8 -*-
from flask import Flask, render_template, redirect, url_for, request, session
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
from flask import Flask, redirect,render_template,request,url_for, send_from_directory
import os


app = Flask(__name__)
app.config['SECRET_KEY'] = 'kkdkdkgllxxlsl'
app.config['PERMANENT_SESSION_LIFETIME'] = 1800
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'  # 使用 SQLite 数据库
#app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True)
    password_hash = db.Column(db.String(100))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)




@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


app.secret_key = 'kdkkgmkriidie8384k'



ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif','webp','pdf'])

app.config['UPLOAD_FOLDER'] = os.getcwd() + '/file'
app.config['MAX_CONTENT_LENGTH'] = 16 * 102400 * 102400


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS



@app.route('/')
def home():
    if 'logged_in' not in session or not session['logged_in']:
        return redirect(url_for('login'))
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            login_user(user)
            session['logged_in'] = True
            session['username'] = request.form['username']
            return redirect(url_for('home'))
        return "用户名或密码错误"
    return render_template('login.html')
@app.route('/register1kdkkdkdkkdkdkdkdllldldldlljvnvnvnrrifmxxm', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if User.query.filter_by(username=username).first():
            return "用户已存在"
        new_user = User(username=username)
        new_user.set_password(password)
        print(new_user)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('login'))
    return render_template('register.html')
    

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    if 'logged_in' not in session or not session['logged_in']:
        return redirect(url_for('login'))
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if 'logged_in' not in session or not session['logged_in']:
        return redirect(url_for('login'))
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            #filename = secure_filename(file.filename)
            filename = file.filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            file_url = url_for('uploaded_file', filename=filename)
            return render_template('upload.html') + '<br><img src=' + file_url + '>'
    return render_template('upload.html')
@app.route('/file_list', methods=['GET', 'POST'])
def file_list():
    if 'logged_in' not in session or not session['logged_in']:
        return redirect(url_for('login'))
    files = os.listdir(app.config['UPLOAD_FOLDER'])
    
    return render_template('file_list.html', file_list=files, )

@app.route('/delete/<filename>')
def delete_file(filename):
    if 'logged_in' not in session or not session['logged_in']:
        return redirect(url_for('login'))
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    if os.path.exists(file_path):
        os.remove(file_path)
        return  redirect(url_for('file_list'))
    else:
        return 'File not found!'

@app.route('/logout')
@login_required
def logout():
    logout_user()
    session['logged_in'] = False
    session['username'] = ''
    return redirect(url_for('login'))


if __name__ == '__main__':
  app.run(host='0.0.0.0', port=8000)
